const Router = require('@koa/router')
const router = new Router()

const db = require('../db')
const { classify } = require('../vri')

router.get('/lazy', async (ctx) => {
  const { query } = ctx
  if (query.number) {
    const ids = await db.find({
      form: 'classify',
      where: {
        grade: 0,
        parent: query.number,
      },
    })
    if (!ids.length)
      return (ctx.body = {
        code: 200,
        data: [],
      })
    const data = await db.find({
      form: 'classify',
      where: {
        grade: 1,
        parent: ids.map((e) => e.id),
      },
      virtual: ['child'],
    })
    ctx.body = {
      code: 200,
      data,
    }
  } else {
    const yd = await db.find({
      form: 'classify',
      where: {
        grade: 0,
      },
    })
    const data = []
    yd.forEach((e) => {
      let ars = data[e.parent]
      if (!ars) {
        ars = []
        data[e.parent] = ars
      }
      ars.push(e)
    })
    ctx.body = {
      code: 200,
      data,
    }
  }
})

// 获取
router.get('/list', async (ctx) => {
  const { query } = ctx
  const { adopt, error, value } = classify.list.verifies(query)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const data = await db.find({
    form: 'classify',
    where: value,
  })
  ctx.body = {
    code: 200,
    data,
  }
})

// 添加
router.post('/add', async (ctx) => {
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { body } = ctx.request
  const { adopt, error, value } = classify.add.verifies(body)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const { lastId: id } = await db.insert({
    form: 'classify',
    value: {
      ...value,
      deleteAt: 0,
    },
    lastId: true,
  })
  await db.insert({
    form: 'classify-record',
    value: {
      ...value,
      type: 'new',
      classifyid: id,
    },
  })
  ctx.body = {
    code: 200,
    msg: '成功',
    id,
  }
})

/**修改分类 */
async function modify(ctx, value, type) {
  const { id } = value
  delete value.id
  const option = {
    form: 'classify',
    where: {
      id,
    },
  }
  const old = await db.first({
    ...option,
  })
  if (!old) return ctx.error(431)
  const lodData = {
    oldname: old.name,
    oldgrade: old.grade,
    oldparent: old.parent,
  }
  const { affectedRows } = await db.update({
    ...option,
    set: value,
  })
  await db.insert({
    form: 'classify-record',
    value: {
      type,
      classifyid: id,
      ...lodData,
      ...value,
    },
  })
  ctx.body = {
    code: 200,
    affectedRows,
  }
}

// 移动分类
router.post('/move', async (ctx) => {
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { body } = ctx.request
  const { adopt, error, value } = classify.move.verifies(body)
  if (!adopt) return ctx.error(430, { error: error.toString() })

  await modify(ctx, value, 'move')
})
// 重命名
router.post('/rename', async (ctx) => {
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { body } = ctx.request
  const { adopt, error, value } = classify.rename.verifies(body)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  await modify(ctx, value, 'rename')
})

// 删除
router.post('/del', async (ctx) => {
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { body } = ctx.request
  const { adopt, error, value } = classify.del.verifies(body)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const { affectedRows } = await db.remove({
    form: 'classify',
    where: {
      id: value.id,
    },
  })
  if (!affectedRows) return ctx.error(431)
  await db.insert({
    form: 'classify-record',
    value: {
      type: 'del',
      classifyid: value.id,
    },
  })
  return (ctx.body = {
    code: 200,
    msg: '成功',
  })
})

// 获取操作记录
router.get('/record', async (ctx) => {
  const { query } = ctx
  const { adopt, error, value } = classify.record.verifies(query)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const data = await db.find({
    form: 'classify-record',
    limit: value,
    order: {
      createdAt: 'DESC',
    },
  })
  const total = await db.count({
    form: 'classify-record',
    limit: value,
  })
  ctx.body = {
    code: 200,
    data,
    total,
  }
})

// 还原操作记录
router.post('/reduction', async (ctx) => {
  const { body } = ctx.request
  const { adopt, error, value } = classify.fromid.verifies(body)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const option = {
    form: 'classify-record',
    where: {
      id: value.id,
    },
  }
  const data = await db.first(option)
  if (data.type === 'del') {
    await db.update({
      form: 'classify',
      where: {
        id: data.classifyid,
        deleteAt: 1,
      },
      set: {
        deleteAt: 0,
      },
    })
  } else if (data.type === 'new') {
    await db.remove({
      form: 'classify',
      where: {
        id: data.classifyid,
      },
    })
    await db.insert({
      form: 'classify-record',
      value: {
        type: 'del',
        classifyid: data.classifyid,
      },
    })
  } else {
    const newData = {
      name: data.oldname,
      grade: data.oldgrade,
      parent: data.oldparent,
    }
    await db.update({
      form: 'classify',
      where: {
        id: data.classifyid,
      },
      set: newData,
    })
  }
  await db.delete(option)
  ctx.body = {
    code: 200,
  }
})

// 批量删除
// router.post('/dels', async (ctx) => {
//   const { user } = ctx.state
//   if (!user) return ctx.error('401')
//   const { body } = ctx.request
//   const { adopt, error, value } = classify.dels.verifies(body)
//   if (!adopt) return ctx.error(430, { error: error.toString() })
//   const { affectedRows } = await db.remove({
//     form: 'classify',
//     where: {
//       id: value.ids,
//       userid: user.id,
//     },
//   })
//   if (!affectedRows) return ctx.error(431)
//   return (ctx.body = {
//     code: 200,
//     msg: '成功',
//   })
// })

// 获取父分类
router.get('/parent', async (ctx) => {
  const { query } = ctx
  const { adopt, error, value } = classify.parent.verifies(query)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const yf = await db.first({
    form: 'classify',
    where: {
      id: value.id,
    },
  })
  if (!yf) return ctx.error(431)
  const data = [yf]
  while (data[0].grade > 0) {
    const cs = await db.first({
      form: 'classify',
      where: {
        id: data[0].parent,
      },
    })
    data.unshift(cs)
  }
  ctx.body = {
    code: 200,
    data,
  }
})
// 获取分类下品牌
router.get('/brand', async (ctx) => {
  const { query } = ctx
  const { adopt, error, value } = classify.fromid.verifies(query)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const data = await db.find({
    form: 'brand',
    where: {
      classifys: {
        met: 'FIND_IN_SET',
        val: value.id,
      },
    },
  })
  ctx.body = {
    code: 200,
    data,
  }
})

module.exports = router.routes()
